// 机构管理工具
import { type Organization } from './organizations.env';
import organizationsData from './organizations.json';

export class OrganizationManager {
  private static instance: OrganizationManager;
  private orgList: Organization[] = [...organizationsData.organizations];

  private constructor() {}

  public static getInstance(): OrganizationManager {
    if (!OrganizationManager.instance) {
      OrganizationManager.instance = new OrganizationManager();
    }
    return OrganizationManager.instance;
  }

  // 获取所有机构
  public getAllOrganizations(): Organization[] {
    return [...this.orgList];
  }

  // 根据账号查找机构
  public findByAccount(account: string): Organization | undefined {
    return this.orgList.find(org => org.account === account);
  }

  // 根据名称查找机构
  public findByName(name: string): Organization | undefined {
    return this.orgList.find(org => org.name === name);
  }

  // 搜索机构
  public search(keyword: string): Organization[] {
    if (!keyword.trim()) {
      return this.getAllOrganizations();
    }
    
    const lowerKeyword = keyword.toLowerCase();
    return this.orgList.filter(org => 
      org.name.toLowerCase().includes(lowerKeyword) || 
      org.account.toLowerCase().includes(lowerKeyword)
    );
  }

  // 添加机构
  public addOrganization(org: Organization): boolean {
    const existing = this.findByAccount(org.account);
    if (existing) {
      console.warn(`机构账号 ${org.account} 已存在`);
      return false;
    }
    
    this.orgList.push(org);
    console.log(`成功添加机构: ${org.name} (${org.account})`);
    return true;
  }

  // 更新机构
  public updateOrganization(account: string, updates: Partial<Organization>): boolean {
    const org = this.findByAccount(account);
    if (!org) {
      console.warn(`机构账号 ${account} 不存在`);
      return false;
    }
    
    Object.assign(org, updates);
    console.log(`成功更新机构: ${org.name} (${org.account})`);
    return true;
  }

  // 删除机构
  public removeOrganization(account: string): boolean {
    const index = this.orgList.findIndex(org => org.account === account);
    if (index === -1) {
      console.warn(`机构账号 ${account} 不存在`);
      return false;
    }
    
    const removed = this.orgList.splice(index, 1)[0];
    console.log(`成功删除机构: ${removed.name} (${removed.account})`);
    return true;
  }

  // 验证机构凭据
  public validateCredentials(account: string, password: string): boolean {
    const org = this.findByAccount(account);
    return org ? org.password === password : false;
  }

  // 获取机构统计信息
  public getStatistics() {
    return {
      total: this.orgList.length,
      accounts: this.orgList.map(org => org.account),
      names: this.orgList.map(org => org.name)
    };
  }

  // 导出机构数据
  public exportToJSON(): string {
    return JSON.stringify({ organizations: this.orgList }, null, 2);
  }

  // 从JSON导入机构数据
  public importFromJSON(jsonData: string): boolean {
    try {
      const data = JSON.parse(jsonData);
      if (data.organizations && Array.isArray(data.organizations)) {
        this.orgList = data.organizations;
        console.log(`成功导入 ${data.organizations.length} 个机构`);
        return true;
      }
      throw new Error('无效的JSON格式');
    } catch (error) {
      console.error('导入机构数据失败:', error);
      return false;
    }
  }

  // 重置为默认配置
  public resetToDefault(): void {
    this.orgList = [...organizationsData.organizations];
    console.log('已重置为默认机构配置');
  }
}

// 导出单例实例
export const organizationManager = OrganizationManager.getInstance();
